package com.leyou.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author zhaoxiaozhao
 * @description ajax跨域请求配置（是否可以通过）
 * @date 2018/11/10 17:29
 */
@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter corsFilter(){
        //1.添加cors的配置信息
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        //2.可以跨域的地址
        corsConfiguration.addAllowedOrigin("http://manage.leyou.com");

        //3.是否可以发送cookie
        corsConfiguration.setAllowCredentials(true);

        //4.可以请求的方式
        corsConfiguration.addAllowedMethod("OPTIONS");
        corsConfiguration.addAllowedMethod("HEAD");
        corsConfiguration.addAllowedMethod("GET");
        corsConfiguration.addAllowedMethod("PUT");
        corsConfiguration.addAllowedMethod("POST");
        corsConfiguration.addAllowedMethod("DELETE");
        corsConfiguration.addAllowedMethod("PATCH");

        //5.允许头信息
        corsConfiguration.addAllowedHeader("*");

        //6.添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource urlBase = new UrlBasedCorsConfigurationSource();
        urlBase.registerCorsConfiguration("/**",corsConfiguration);

        //7.返回新的corsFilter
        return new CorsFilter(urlBase);
    }

}